#!/usr/bin/env python
# coding:utf-8

from __future__ import print_function
import sys
import getopt
import string
import os
from apk_search import apk_search
from multiprocessing import Pool

def apks_search(apk_list, keywords, case_sensitive, process_num, search_all, use_fetcher):
    result_list = []
    if process_num == 1:
        for h in apk_list:
            result = apk_search(h, keywords, case_sensitive, search_all, use_fetcher)
            if result:
                result_list.append(h)
    else:
        p = Pool(process_num)
        results = []
        for i in range(process_num):
            l = len(apk_list)
            st = l // process_num * i
            en = l // process_num * (i + 1)
            if i == process_num - 1:
                en = l
            print (str(st) + " " + str(en))
            results.append(p.apply_async(apks_search, (apk_list[st:en], keywords, case_sensitive, 1, search_all, use_fetcher)))
        p.close()
        p.join()
        for result in results:
            result_list += result.get()
    return result_list

if __name__ == '__main__':
    try:
        options, args = getopt.getopt(sys.argv[1:], "sah:m:d:")
    except getopt.GetoptError:
        print ("Usage: apks_search.py (-s)(-a)-m[multiprocess_num]-h[hash_list_path] or -d[apk_folder] [keyword1] [keyword2]...")
        print ("-s for case sensitive, -a to search all files in an apk(will stop on first keyword found by default)")
        sys.exit()

    case_sensitive = False
    search_all = False
    file_path = ""
    use_fetcher = False
    process_num = 1
    for option, value in options:
        if option == "-s":
            case_sensitive = True
        elif option == "-m":
            process_num = string.atoi(value)
        elif option == "-h":
            file_path = value
            use_fetcher = True
        elif option == "-d":
            file_path = value
            use_fetcher = False
        elif option == "-a":
            search_all = True

    keywords = args
    apk_list = []
    if use_fetcher:
        apk_list = [line.strip('\n') for line in open(file_path) ]
    else:
        for root, dirs, files in os.walk(file_path):
            for f in files:
                if os.path.splitext(f)[1] == '.apk':
                    apk_list.append(os.path.join(root, f) )
    print (apks_search(apk_list, keywords, case_sensitive, process_num, search_all, use_fetcher) )

